<template>
    <div>
        <div class="risk-custom-select" v-if="!disabled">
            <el-popover ref="popover" placement="bottom" width="300" trigger="click" v-model="visible" @hide="hide" @show="show">
                <div style="padding: 2px 0; hegiht: 42px" :style="{ display: showSearch ? '' : 'none' }">
                    <el-input v-model="state.searchValue" @keyup.native="handleSearchSort" placeholder="请选择" size="mini">
                        <i class="el-icon-search" slot="prefix" style="cursor: pointer" @click="handleSearchSort"></i>
                    </el-input>
                </div>
                <div style="max-height: 200px; overflow: auto">
                    <el-checkbox-group
                        v-model="state.inputValueList"
                        size="mini"
                        @change="handleCheckBox"
                        style="display: flex; flex-direction: column"
                        class="checkbox-content"
                    >
                        <el-checkbox v-for="item in filterDataSource" :key="item.dictKey" :label="item.dictKey" :name="'boundValues' + item.dictKey">
                            {{ item.dictKey + '  ' + item.dictKeyName }}</el-checkbox
                        >
                    </el-checkbox-group>
                </div>
                <el-input
                    :name="nameIdt"
                    v-model="state.inputValueText"
                    slot="reference"
                    :placeholder="placeholder"
                    @keyup.native="handleInputChange"
                    size="mini"
                    @click="click"
                    @focus="focus"
                    @blur="blur"
                    :disabled="disabled"
                ></el-input>
            </el-popover>
        </div>
        <div v-else>
            <el-input
                :name="nameIdt"
                v-model="state.inputValueText"
                slot="reference"
                :placeholder="placeholder"
                @keyup.native="handleInputChange"
                size="mini"
                @click="click"
                @focus="focus"
                @blur="blur"
                :disabled="disabled"
            ></el-input>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { makePy } from '@/cache/pinyin';
import { UUID12 } from '@/utils/tools';
import { warn } from 'vue-class-component/lib/util';
@Component({
    name: 'RiskCustomSelect',
    components: {},
})
/**
 * 属性
 * selectKeys 选中的key item.dictKey + ' ' + item.dictKeyName
 * dataSource 下拉列表集合 格式 = [{dictKey：'',dictKeyName:''}]
 * showSelectAll 是否显示全选 全选为-1
 * show3Row 是否允许3列展示
 * settingValue(keys) 回调函数
 * showKey 显示的key字段（可能有些东西要做适配key用来显示给用户看，但是实际操作的还是dictKey）
 * nameIdt:自动化测试标识名
 */
export default class RiskCustomSelect extends Vue {
    @Prop() selectKeys;
    @Prop() dataSource;
    @Prop() showSelectAll;
    @Prop() showKey;
    @Prop() show3Row;
    @Prop() showSearch;
    @Prop({ default: '请选择' }) placeholder: string;
    @Prop({ default: false }) disabled: boolean;
    @Prop() nameIdt: string;
    state = {
        dataSource: [], // 下拉列表值
        showOption: false, // 是否显示下拉列表信息
        inputValueList: [], // 选择的值集合
        inputValueText: '',
        searchValue: '', // 搜索框的值
    };

    name = {
        uuid: '',
        dataOption: [], // 可选下拉数据列表
        isInputFocus: false, // 是否聚焦
        isMouseEnter: false, // 鼠标是否在选项中
        isDivFocus: false, // 选择面板是否聚焦
        showSelectAll: false,
        show3Row: false,
        renderUUID12: '-1',
        showKey: 'dictKey',
    };
    private visible: boolean = false; // 是否显示下拉框

    private filterDataSource: any[] = [];

    private keyNum: number = -1; // 标记
    focusState: boolean = false;

    mounted() {
        // this.name.showSelectAll = this.showSelectAll === true;
        // this.state.selectKeys = this.selectKeys || [];
        this.name.showSelectAll = this.showSelectAll;
        this.name.show3Row = this.show3Row === true;
        if (this.showKey !== undefined && this.showKey !== null) {
            this.name.showKey = this.showKey;
        } else {
            this.name.showKey = 'dictKey';
        }
        this.name.renderUUID12 = UUID12();
        this.renderListInfo(this.state.dataSource, this.name.showSelectAll, this.selectKeys);
    }

    @Watch('dataSource', { immediate: true })
    handleDataSource() {
        this.state.dataSource = JSON.parse(JSON.stringify(this.dataSource || []));
        this.handleSearchSort();
    }

    /**
     * 处理需要渲染的数据信息
     */
    private renderListInfo(dataSource, showSelectAll, selectKeys) {
        if (!dataSource) {
            return;
        }
        if (showSelectAll) {
            dataSource.unshift({ dictKey: '-1', dictKeyName: '全部选择' });
            dataSource[0][this.name.showKey] = '-1';
        }
        this.state.inputValueList = [];
        let rDataSource = [];
        for (let i = 0; i < dataSource.length; i++) {
            let dataTemp = dataSource[i];
            if (selectKeys.includes(dataSource[i].dictKey)) {
                this.state.inputValueList.push(dataTemp[this.name.showKey]);
                rDataSource.push(dataTemp);
            } else {
                rDataSource.push(dataTemp);
            }
        }
        this.state.dataSource = rDataSource;

        this.state.inputValueText = this.state.inputValueList.join(',');
        // this.handleCheckBox(this.state.inputValueList); //
        this.getIdAndName();
    }

    /**
     * 多选框选择事件
     */
    private handleCheckBox(checked) {
        if (checked) {
            if (checked.length > 1 && checked[0] === '-1' && this.name.showSelectAll) {
                this.state.inputValueList = ['-1'];
                this.$message.warning('选择全选后，不可再选择其他值');
            }
            if (checked.length > 1 && checked[checked.length - 1] === '-1' && this.name.showSelectAll) {
                this.state.inputValueList = ['-1'];
                this.$message.info('选择全选后,其他选项自动清空');
            }
            this.state.inputValueText = this.state.inputValueList.join(',');
        }
        this.$emit('customSelectReturn', this.state.inputValueList);
    }
    /**
     *  搜索函数
     */
    private handleSearchSort() {
        if (!this.state.searchValue) {
            this.filterDataSource = JSON.parse(JSON.stringify(this.state.dataSource));
            return;
        }
        let key = [];
        let value = [];
        let pinyinValue = [];
        let inputUpper = this.state.searchValue.toUpperCase();
        for (let item of this.state.dataSource) {
            if (item[this.name.showKey].includes(this.state.searchValue)) {
                key.push(item);
            } else if (item.dictKeyName.includes(this.state.searchValue)) {
                value.push(item);
            } else {
                let pyArr = makePy(item.dictKeyName);

                for (let i = 0; i < pyArr.length; i++) {
                    if (pyArr[i].includes(inputUpper)) {
                        pinyinValue.push(item);
                        break;
                    }
                }
            }
        }
        this.filterDataSource = key.concat(value, pinyinValue);
    }

    /**
     * 输入框事件
     */
    private handleInputChange() {
        let value = this.state.inputValueText;
        let c = [];
        if (value) {
            c = value.split(',');
            if (this.name.showSelectAll && c.includes('-1')) {
                let a1 = c.filter(item => !!item);
                if (a1.length > 1) {
                    // this.$message.info('当选择其他选项时，不可录入全选(-1)');
                    this.$message.info('当选择全选(-1)时,其他选项自动清空');
                    this.state.inputValueList = ['-1'];
                    this.state.inputValueText = '-1';
                    return;
                }
            }
            this.state.inputValueList = this.state.dataSource
                .filter(item => c.includes(item[this.name.showKey]))
                .map(item => item[this.name.showKey]);
            let keyNameList = this.state.dataSource
                .filter(item => c.includes(item['dictKeyName']))
                .map(item => item[this.name.showKey]);
            this.state.inputValueList = this.state.inputValueList.concat(keyNameList);
        } else {
            this.state.inputValueList = [];
        }
        this.$emit('customSelectReturn', this.state.inputValueList);
    }

    // 弹出框显示时触发
    private show(): void {
        // console.log('showDialog');
    }

    // 弹出框隐藏时触发
    private hide(): void {
        // console.log('hideDialog');
        // console.log((this.$refs as any).popover.doClose);
        if (this.focusState) {
            (this.$refs as any).popover.showPopper = true;
        }
        this.keyNum++;
        // console.log((this.$refs as any).popover.showPopper, this.keyNum, 'hide');

        this.$nextTick(() => {
            setTimeout(() => {
                if (this.keyNum % 2 == 1 && (this.$refs as any).popover && !(this.$refs as any).popover.showPopper) {
                    this.getIdAndName();
                }
            }, 1000);
        });
    }

    private click() {
        this.visible = true && !this.disabled;
    }

    // 获取焦点
    private focus() {
        this.focusState = true;
        // this.visible = true && !this.disabled;
        this.handleCheckBox(this.state.inputValueList);
    }

    // 失去焦点
    private blur() {
        this.focusState = false;
        (this.$refs as any).popover.showPopper = true;
    }

    private getIdAndName(): void {
        this.keyNum++;
        let list;
        let name = [];
        // console.log(this.state.inputValueList);

        if (this.state.inputValueList.includes('-1')) {
            this.state.inputValueText = '-1(全部选择)';
            return;
        }
        this.state.inputValueList.forEach(ele => {
            list = this.dataSource.find(item => item.dictKey == ele);
            name.push(ele + '(' + list.dictKeyName + ')');
        });
        this.state.inputValueText = name.join(',');
    }
}
</script>
<style lang="scss" scoped>
/deep/ .el-input__prefix {
    top: 5px;
}

.checkbox-content /deep/ .el-checkbox {
    padding: 4px 3px 4px 0px;
    &:hover {
        background-color: #f3f6fe;
        color: #50a6ff;
    }
}
</style>
<style lang="scss">
.el-popover {
    max-height: 300px;
    overflow: inherit;
    padding: 10px 2px 10px 15px !important;
}
</style>
